package com.hunk.core.auth.repository;

import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import com.hunk.core.auth.entity.User;
import com.hunk.core.auth.entity.User_;

/**
 * Description :<br>
 * 
 * @author HunkDeng
 * @since 2013-4-30
 */
public class RoleSpecifications {
	/**
     * @param searchTerm    
     * 	The used search term.
     * @return
     */
    public static Specification<User> UserSpecQueryOne(final Map<String, Object> params) {
        return new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, 
            		CriteriaBuilder criteriaBuilder) {
            	String username = (String)params.get("username");
            	String realname = (String)params.get("realname");
            	/* User_.class Must store with User.class in same package.
            	 * Otherwise, It's will throw a NPE
            	 */
            	Predicate predicate = criteriaBuilder.conjunction();
                if (StringUtils.hasText(username)) {
                	predicate.getExpressions().add(
                	criteriaBuilder.like(root.<String>get(User_.username),
                			getContainPattern(username))
                  );
                }
                if (StringUtils.hasText(realname)) {
                	predicate.getExpressions().add(
                	criteriaBuilder.like(root.<String>get(User_.realname),
                			getContainPattern(StringUtils.trimWhitespace(realname)))
                  );
                }
                return predicate;
             }

            private String getContainPattern(final String searchTerm) {
                return "%" + searchTerm.toLowerCase() + "%";
            }
        };
    }
}
